﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


namespace Loong.Store
{
    /// <summary>
    /// 对象实例以Queue形式存储到物理文件
    /// </summary>
    [Serializable]
    public class ObjectStoreQueue:Queue,IObjectStore
    {
        private string filename;

        public ObjectStoreQueue(string filename):base()
        {            
            this.filename = filename;
        }


        /// <summary>
        /// 
        /// </summary>
        public void Load()
        {
            if (!File.Exists(filename))
                return;

            Stream stream = new FileStream(this.filename, FileMode.Open, FileAccess.Read, FileShare.None);
            if (stream != null)
            {
                try
                {
                  
                    IFormatter formatter = new BinaryFormatter();
                    Queue appData = (Queue)formatter.Deserialize(stream);
                    //this = appData;不直接赋值

                    for (int i = 0; i < appData.Count; i++)
                    {
                        appData.Enqueue(appData.Dequeue());
                    }                  
                   
                }
                finally
                {
                    stream.Close();
                }
            }
        }

        public void Save()
        {
            Stream stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            if (stream != null)
            {
                try
                {
                    // Serialize the Hashtable into the IsolatedStorage.
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, (Queue)this);
                }
                finally
                {
                    stream.Close();
                }
            }
        }


    }
}
